<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑模板</title>
    <link href="../../../layui/css/layui.css" rel="stylesheet">
    <link href="../../../static/css/style.css" rel="stylesheet">
    <script src="../../../static/js/jquery.min.js"></script>
    <script src="../../../static/js/jquery.cookie.js"></script>
    <script src="../../../layui/layui.js"></script>
    <script src="../../../static/js/base.js"></script>
    <script src="../../../static/js/ax.js"></script>
    <!--[if lt IE 9]>
    <script src="../../../static/js/html5.js"></script>
    <script src="../../../static/js/respond.js"></script>
    <![endif]-->

    <style type="text/css">
        .dataItem i {
            display: none;
        }
        .dataItem.selected i {
            display: inline;
        }
    </style>
</head>

<body class="bg_w">
<div class="content-wrap">
    <div class="layui-row">
        <form class="layui-form layui-form-pane" id="from1">
            <input type="hidden" id="dataId" value="" />
            <div class="layui-row layui-col-space10">
                <div class="layui-col-sm6" id="templateCodeItem" style="display: none">
                    <label class="layui-form-label">模板编号</label>
                    <div class="layui-input-block">
                        <input type="text"  id="templateCode" class="layui-input" lay-verify="required" maxlength="100" placeholder="请输入模板标题">
                    </div>
                </div>
                <div class=" layui-col-sm12">
                    <label class="layui-form-label">模板标题</label>
                    <div class="layui-input-block">
                        <input type="text"  id="templateTitle" class="layui-input" lay-verify="required" maxlength="100" placeholder="请输入模板标题">
                    </div>
                </div>
                <div class=" layui-col-sm12">
                    <div class="layui-form-item" pane="">
                        <label class="layui-form-label">推送方式</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="pushType" value="app" title="APP" lay-skin="primary" />
                            <input type="checkbox" name="pushType" value="wx_public" title="微信公众号" lay-skin="primary" />
                            <input type="checkbox" name="pushType" value="wx_applet" title="微信小程序" lay-skin="primary" />
                            <!--<input type="checkbox" name="pushType" value="sms" title="短信" lay-skin="primary" />-->
                        </div>
                    </div>

                </div>
                <div class="layui-col-sm12 layui-col-space15 templateContent" id="templateContentForApp" style="display: none">
                    <div class="layui-col-sm6 layui-form-text">
                        <label class="layui-form-label">APP模板内容</label>
                        <div class="layui-input-block">
                            <textarea placeholder="请输入APP模板内容" class="layui-textarea" style="max-height: 200px;"></textarea>
                        </div>
                    </div>
                    <div class="layui-col-sm6 layui-form-text">
                        <label class="layui-form-label">模板参数</label>
                        <div class="contentParamList">
                            <!--<div class="dataItem">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                            <!--</div>-->
                            <!--<div class="dataItem">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                            <!--</div>-->
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm12 layui-col-space15 templateContent" id="wxTemplateForPublic" style="display: none">
                    <div class="layui-col-sm6">
                        <label class="layui-form-label">公众号消息模板ID</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input wxTemplateId" maxlength="100" placeholder="请输入公众号模板ID" />
                        </div>
                    </div>
                    <div class="layui-col-sm6">
                        <label class="layui-form-label">公众号跳转链接</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input wxLinkUrl" maxlength="200" placeholder="请输入公众号跳转链接" />
                        </div>
                    </div>
                    <div class="layui-col-sm6 layui-form-text">
                        <label class="layui-form-label">公众号模板内容</label>
                        <div class="layui-input-block">
                            <textarea placeholder="请输入公众号模板内容(推送预览用)" class="layui-textarea" style="max-height: 200px;"></textarea>
                        </div>
                    </div>
                    <div class="layui-col-sm6">
                        <label class="layui-form-label">模板参数</label>
                        <div class="contentParamList">
                            <!--<div class="dataItem">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                            <!--</div>-->
                            <!--<div class="dataItem selected">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                                <!--<i class="layui-icon layui-icon-ok"></i>-->
                            <!--</div>-->
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm12 layui-col-space15 templateContent" id="wxTemplateForApplet" style="display: none">
                    <div class="layui-col-sm6">
                        <label class="layui-form-label">小程序消息模板ID</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input wxTemplateId" lay-verify="required" maxlength="100" placeholder="请输入小程序模板ID" />
                        </div>
                    </div>
                    <div class="layui-col-sm6">
                        <label class="layui-form-label">小程序跳转链接</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input wxLinkUrl" lay-verify="required" maxlength="200" placeholder="请输入小程序跳转链接" />
                        </div>
                    </div>
                    <div class="layui-col-sm6 layui-form-text">
                        <label class="layui-form-label">小程序模板内容</label>
                        <div class="layui-input-block">
                            <textarea placeholder="请输入小程序模板内容(推送预览用)" class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <div class="layui-col-sm6 layui-form-text">
                        <label class="layui-form-label">模板参数</label>
                        <div class="contentParamList">
                            <!--<div class="dataItem">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                            <!--</div>-->
                            <!--<div class="dataItem selected">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                                <!--<i class="layui-icon layui-icon-ok"></i>-->
                            <!--</div>-->
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm12 layui-col-space15 templateContent" id="templateContentForSms" style="display: none">
                    <div class="layui-col-sm6 layui-form-text">
                        <label class="layui-form-label">短信模板内容</label>
                        <div class="layui-input-block">
                            <textarea placeholder="请输入短信模板内容" class="layui-textarea" style="max-height: 200px;"></textarea>
                        </div>
                    </div>
                    <div class="layui-col-sm6">
                        <label class="layui-form-label">模板参数</label>
                        <div class="contentParamList">
                            <!--<div class="dataItem">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                            <!--</div>-->
                            <!--<div class="dataItem">-->
                                <!--<label class="itemLabel">姓名：（[{$name}]）</label>-->
                            <!--</div>-->
                        </div>
                    </div>
                </div>

                <div class="layui-col-sm12 layui-form-text">
                    <label class="layui-form-label">驾校选择</label>
                    <div class="layui-input-block">
                        <div class="layui-textarea dsList">
                            <!--001-渝北驾校,002-渝北驾校-->
                        </div>
                        <span class="layui-layout-right dsCount" style="bottom: 10px;right:10px;top: auto">0个驾校</span>
                    </div>
                </div>
            </div>

            <div class="layui-input-block">
                <button type="button" id="btnClose" class="layui-btn layui-btn-primary btn-left">关闭</button>
                <button type="button" id="btnSubmit" class="layui-btn add_btn btn-left">提交</button>
            </div>


        </form>
    </div>
</div>
</body>

<script>

    var templateData = null;
    var baseDataDone = false;
    var dsList = [];
    var appParamList = [];
    var publicParamList = [];
    var appletParamList = [];
    var smsParamList = [];
    var $;
    layui.use(['form','layer'], function() {
        $ = layui.$;
        var form = layui.form,
            layer=layui.layer;

        form.on('checkbox', function(data){
            var pushType = data.value;
            var isCheck = data.elem.checked;
            if(pushType == "app") {
                if(isCheck) {
                    $("#templateContentForApp").show();
                } else {
                    $("#templateContentForApp").hide();
                }
            } else if (pushType == "wx_public") {
                if(isCheck) {
                    $("#wxTemplateForPublic").show();
                } else {
                    $("#wxTemplateForPublic").hide();
                }
            } else if (pushType == "wx_applet") {
                if(isCheck) {
                    $("#wxTemplateForApplet").show();
                } else {
                    $("#wxTemplateForApplet").hide();
                }
            } else if (pushType == "sms") {
                if(isCheck) {
                    $("#templateContentForSms").show();
                } else {
                    $("#templateContentForSms").hide();
                }
            }
        });

        $("#templateContentForApp .contentParamList").on("click", ".dataItem", function () {
            // 追加到模板中
            var paramObj = $(this).data("data");
            var $input = $(this).parents(".templateContent").find("textarea");
            $input.val($input.val() + paramObj.mtpItem);

            // 设置选中
            if(!$(this).hasClass("selected")) {
                $(this).addClass("selected");
            }

            // 添加到参数列表
            // var result = appParamList.some(item=>{
            //     if(item.mtpId == paramObj.id){
            //         return true
            //     }
            // });

            var result = appParamList.some(function (item) {
                if(item.mtpId == paramObj.id){
                            return true
                        }
            });

            if(!result) {
                appParamList.push({
                    mtpId: paramObj.id,
                    mtpItem: paramObj.mtpItem,
                    mtpDesc: paramObj.mtpDesc
                });
            }
        });

        $("#templateContentForSms .contentParamList").on("click", ".dataItem", function () {
            // 追加到模板中
            var paramObj = $(this).data("data");
            var $input = $(this).parents(".templateContent").find("textarea");
            $input.val($input.val() + paramObj.mtpItem);

            // 设置选中
            if(!$(this).hasClass("selected")) {
                $(this).addClass("selected");
            }

            // 添加到参数列表
            // var result = smsParamList.some(item=>{
            //     if(item.mtpId == paramObj.id){
            //         return true
            //     }
            // });
            var result = smsParamList.some(function (item) {
                if(item.mtpId == paramObj.id){
                          return true
                        }
            })
            if(!result) {
                smsParamList.push({
                    mtpId: paramObj.id,
                    mtpItem: paramObj.mtpItem,
                    mtpDesc: paramObj.mtpDesc
                });
            }
        });

        $("#wxTemplateForPublic .contentParamList").on("click", ".dataItem", function () {
            $(this).toggleClass("selected");

            // 添加或移除
            var paramObj = $(this).data("data");
            if($(this).hasClass("selected")) {
                publicParamList.push({
                    mtpId: paramObj.id,
                    mtpItem: paramObj.mtpItem,
                    mtpDesc: paramObj.mtpDesc
                });
            } else {
                $.each(publicParamList, function (index, paramData) {
                    if(paramData.mtpId == paramObj.id) {
                        publicParamList.splice(index, 1);
                    }
                });
            }
        });

        $("#wxTemplateForApplet .contentParamList").on("click", ".dataItem", function () {
            $(this).toggleClass("selected");

            // 添加或移除
            var paramObj = $(this).data("data");
            if($(this).hasClass("selected")) {
                appletParamList.push({
                    mtpId: paramObj.id,
                    mtpItem: paramObj.mtpItem,
                    mtpDesc: paramObj.mtpDesc
                });
            } else {
                $.each(appletParamList, function (index, paramData) {
                    if(paramData.mtpId == paramObj.id) {
                        appletParamList.splice(index, 1);
                    }
                });
            }
        });

        $('.dsList').on('click', function () {

            layer.open({
                type: 2,
                area: ['90%', '80%'],
                title:'选择驾校',
                fixed: true, //不固定
                maxmin: true,
                content: '../../common/selectDriverSchool.html?isBatch=1'
            });
        });

        $('#btnClose').on("click", function () {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        });

        $('#btnSubmit').on('click', function(){
            var mtData = {
                id:$("#dataId").val(),
                mtTitle:$("#templateTitle").val(),
                pushTypeList:[],
                mtDriverSchoolList:dsList
            };

            $("input:checkbox[name='pushType']:checked").each(function(i){
                var pushTypeObj = {
                    pushType: $(this).val()
                };
                if(pushTypeObj.pushType == "app") {
                    // APP
                    pushTypeObj.mtContent = $("#templateContentForApp textarea").val();
                    pushTypeObj.pushParamList = appParamList;
                } else if(pushTypeObj.pushType == "wx_public") {
                    // 微信公众号
                    pushTypeObj.mtWxTemplateId = $("#wxTemplateForPublic .wxTemplateId").val();
                    pushTypeObj.mtUrl = $("#wxTemplateForPublic .wxLinkUrl").val();
                    pushTypeObj.mtContent = $("#wxTemplateForPublic textarea").val();
                    pushTypeObj.pushParamList = publicParamList;
                } else if(pushTypeObj.pushType == "wx_applet") {
                    // 微信小程序
                    pushTypeObj.mtWxTemplateId = $("#wxTemplateForApplet .wxTemplateId").val();
                    pushTypeObj.mtUrl = $("#wxTemplateForApplet .wxLinkUrl").val();
                    pushTypeObj.mtContent = $("#wxTemplateForApplet textarea").val();
                    pushTypeObj.pushParamList = appletParamList;
                } else if(pushTypeObj.pushType == "sms") {
                    // 短信
                    pushTypeObj.mtContent = $("#templateContentForSms textarea").val();
                    pushTypeObj.pushParamList = smsParamList;
                }
                mtData.pushTypeList.push(pushTypeObj);
            });

            if(checkData(mtData)) {
                saveData(mtData);
            }
        });

        var initBaseData = function () {
            ax.get({
                autoPrefix: false,
                url : backendWebUrl + '/api/message/param/listAll',
                success: function (res) {
                    if (res.code == 0) {
                        loadBaseData(res.data);
                    } else {
                        layer.msg(res.message);
                    }
                }

            });
        };

        var loadBaseData = function (baseData) {
            // 初始化模板参数
            $(".contentParamList").empty();
            $.each(baseData, function (index, param) {
                var html = [];
                html.push("<div class='dataItem'>");
                html.push(" <label class='itemLabel'>" + param.mtpDesc + "：（[" + param.mtpItem + "]）</label>");
                html.push(" <i class='layui-icon layui-icon-ok'></i>");
                html.push("</div>");

                var $item = $(html.join(""));
                $item.data("data", param);
                $(".contentParamList").append($item);
            });
            baseDataDone = true;
            loadSelectSelected();
        };

        var loadSelectSelected = function () {
            if(baseDataDone && templateData != null) {
                // 设置选中的APP推送参数
                $("#templateContentForApp .contentParamList .dataItem").each(function () {
                   var $item = $(this);
                   var itemParam = $item.data("data");
                   $.each(appParamList, function (index, paramObj) {
                       if(itemParam.id == paramObj.mtpId) {
                           $item.addClass("selected");
                           return false;
                       }
                   });
                });
                // 设置选中的公众号推送参数
                $("#wxTemplateForPublic .contentParamList .dataItem").each(function () {
                    var $item = $(this);
                    var itemParam = $item.data("data");
                    $.each(publicParamList, function (index, paramObj) {
                        if(itemParam.id == paramObj.mtpId) {
                            $item.addClass("selected");
                            return false;
                        }
                    });
                });
                // 设置选中的小程序推送参数
                $("#wxTemplateForApplet .contentParamList .dataItem").each(function () {
                    var $item = $(this);
                    var itemParam = $item.data("data");
                    $.each(appletParamList, function (index, paramObj) {
                        if(itemParam.id == paramObj.mtpId) {
                            $item.addClass("selected");
                            return false;
                        }
                    });
                });
                // 设置选中的短信推送参数
                $("#templateContentForSms .contentParamList .dataItem").each(function () {
                    var $item = $(this);
                    var itemParam = $item.data("data");
                    $.each(smsParamList, function (index, paramObj) {
                        if(itemParam.id == paramObj.mtpId) {
                            $item.addClass("selected");
                            return false;
                        }
                    });
                });
            }
        };

        var initPage = function(dataId) {
            ax.get({
                autoPrefix: false,
                url : backendWebUrl + '/api/message/template/detail',
                data: {dataId:dataId},
                success: function (res) {
                    if (res.code == 0) {
                        templateData = res.data;
                        loadPage();
                    } else {
                        layer.msg(res.message);
                    }
                }

            });
        };
        var loadPage = function () {
            $("#templateCode").val(templateData.messageTemplate.mtCode);
            $("#templateCodeItem").show();
            $("#templateTitle").val(templateData.messageTemplate.mtTitle);

            // 加载模板内容
            $.each(templateData.pushTypeList, function (index, pushType) {
                if(pushType == "app") {
                    // APP
                    $("#templateContentForApp textarea").val(templateData.mtContentForApp);
                    $("#templateContentForApp").show();
                    $("input:checkbox:eq(0)").prop("checked", true);
                    appParamList = templateData.appPushParamList;
                } else if(pushType == "wx_public") {
                    // 微信公众号
                    $("#wxTemplateForPublic .wxTemplateId").val(templateData.mtWxTemplateIdForPublic);
                    $("#wxTemplateForPublic .wxLinkUrl").val(templateData.mtUrlForPublic);
                    $("#wxTemplateForPublic textarea").val(templateData.mtContentForPublic);
                    $("#wxTemplateForPublic").show();
                    $("input:checkbox:eq(1)").prop("checked", true);
                    publicParamList = templateData.publicPushParamList;
                } else if(pushType == "wx_applet") {
                    // 微信小程序
                    $("#wxTemplateForApplet .wxTemplateId").val(templateData.mtWxTemplateIdForApplet);
                    $("#wxTemplateForApplet .wxLinkUrl").val(templateData.mtUrlForApplet);
                    $("#wxTemplateForApplet textarea").val(templateData.mtContentForApplet);
                    $("#wxTemplateForApplet").show();
                    $("input:checkbox:eq(2)").prop("checked", true);
                    appletParamList = templateData.appletPushParamList;
                } else if(pushType == "sms") {
                    // 短信
                    $("#templateContentForSms textarea").val(templateData.mtContentForSms);
                    $("#templateContentForSms").show();
                    $("input:checkbox:eq(3)").prop("checked", true);
                    smsParamList = templateData.smsPushParamList;
                }
            });
            form.render("checkbox");
            loadSelectSelected();
            // 加载分配驾校列表
            dsList = templateData.driverSchoolInfoList;
            loadDSList();
        };
        // 编辑初始化数据
        var dataId = getQueryString("id");
        $("#dataId").val(dataId);
        if(dataId != null && dataId != "") {
            // 有ID，为编辑
            initPage(dataId);
        }
        initBaseData();
    });

    function loadDSList() {
        var dsStr = "";
        $.each(dsList, function (index, dsObj) {
            if(dsStr.length > 0) {
                dsStr += ",";
            }
            dsStr += dsObj.dsCode + "-" + dsObj.dsName;
        });

        $(".dsList").text(dsStr);
        $(".dsCount").text(dsList.length + "个驾校");
    }

    function checkData(mtData) {
        var checkResult = true;
        if(mtData.mtTitle.length == 0) {
            layer.msg("模板标题不能为空");
            checkResult = false;
        } else if(mtData.pushTypeList.length == 0) {
            layer.msg("推送方式不能为空");
            checkResult = false;
        } else if(mtData.mtDriverSchoolList.length == 0) {
            layer.msg("分配驾校不能为空");
            checkResult = false;
        } else {
            $.each(mtData.pushTypeList, function (index, pushContent) {
                if(pushContent.pushType == "app") {
                    if(pushContent.mtContent.length == 0) {
                        layer.msg("APP消息模板不能为空");
                        checkResult = false;
                    }
                } else if(pushContent.pushType == "wx_public") {
                    // 微信公众号
                    if(pushContent.mtWxTemplateId.length == 0) {
                        layer.msg("微信公众号模板ID不能为空");
                        checkResult = false;
                    }
                } else if(pushContent.pushType == "wx_applet") {
                    // 微信小程序
                    if(pushContent.mtWxTemplateId.length == 0) {
                        layer.msg("微信小程序模板ID不能为空");
                        checkResult = false;
                    }
                } else if(pushContent.pushType == "sms") {
                    // 短信
                    if(pushContent.mtContent.length == 0) {
                        layer.msg("短信消息模板不能为空");
                        checkResult = false;
                    }
                }
                if(!checkResult) {
                    return false;
                }
            });
        }
        return checkResult;
    }
    function saveData(mtData) {

        var dataId = $("#dataId").val();
        if(dataId != null && dataId != "") {
            ax.post({
                autoPrefix: false,
                url : backendWebUrl + '/api/message/template/update',
                data: JSON.stringify(mtData),
                success: function (res) {
                    if (res.code == 0) {
                        topFrame.location.reload();
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    } else {
                        layer.msg(res.message);
                    }
                }

            });
        } else {
            ax.post({
                autoPrefix: false,
                url : backendWebUrl + '/api/message/template/add',
                data: JSON.stringify(mtData),
                success: function (res) {
                    if (res.code == 0) {
                        topFrame.location.reload();
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    } else {
                        layer.msg(res.message);
                    }
                }

            });
        }
    }

    function selectDriverSchool(driverSchoolList) {
        dsList = [];
        $.each(driverSchoolList, function (index, ds) {
            dsList.push({
                dsId:ds.id,
                dsCode:ds.code,
                dsName:ds.name
            });
        });
        loadDSList();
    }
</script>


</html>